import { makeAutoObservable } from 'mobx'

export default class LayoutStore implements LayoutStoreTypes.LayoutStore {
  rootStore: any
  tabs = JSON.parse(window.sessionStorage.getItem('ADMIN_LOCAL_TABS') || '[]') as UserStoreTypes.PermissionItemProps[]

  constructor (rootStore: any) {
    makeAutoObservable(this, { rootStore: false })
    this.rootStore = rootStore
  }

  addTab (tab: UserStoreTypes.PermissionItemProps): void {
    const targetIndex = this.tabs.findIndex(item => item.url === tab.url)
    if (targetIndex === -1) {
      this.tabs.push(tab)
      window.sessionStorage.setItem('ADMIN_LOCAL_TABS', JSON.stringify(this.tabs))
    }
  }

  removeTab (tab: UserStoreTypes.PermissionItemProps): void {
    const targetIndex = this.tabs.findIndex(item => item.url === tab.url)
    if (targetIndex > -1) {
      this.tabs.splice(targetIndex, 1)
      window.sessionStorage.setItem('ADMIN_LOCAL_TABS', JSON.stringify(this.tabs))
    }
  }

  clearTabs (): void {
    this.tabs = []
    window.sessionStorage.setItem('ADMIN_LOCAL_TABS', JSON.stringify(this.tabs))
  }
}
